import { render_checkerboard, render_piece } from './render.js'
import { $, size_info, init_map, $$, is_over } from './utils.js'

function bind_event(ctx) {
    function play(e) {
        const rect = this.getBoundingClientRect(),
            left = rect.left,
            top = rect.top
        const side = size_info[ctx.mode].side
        const x = Math.round((e.pageX - left) / side),
            y = Math.round((e.pageY - top) / side)
        if (ctx.map[y][x] !== 0) return;

        ctx.map[y][x] = ctx.next_piece
        render_piece(y, x, side, ctx.next_piece)
        ctx.next_piece = ctx.next_piece === 1 ? 2 : 1
        const result = is_over(ctx.map)
        if (result) {
            $('.mask span').innerHTML = (result === 1 ? '黑' : '白') + '棋胜利！'
            $('.mask').style.display = 'block'
            $('#game').onclick = null
        }
    }

    $('.easy-btn').onclick = () => {
        ctx.mode = 'easy'
        render_checkerboard('easy')
        $('.reset-btn').click()
    }

    $('.plain-btn').onclick = () => {
        ctx.mode = 'plain'
        render_checkerboard('plain')
        $('.reset-btn').click()
    }

    $('.hard-btn').onclick = () => {
        ctx.mode = 'hard'
        render_checkerboard('hard')
        $('.reset-btn').click()
    }

    $('.reset-btn').onclick = () => {
        // 移除所有棋子
        $$('#game .piece').forEach(item => {
            item.remove()
        })
        ctx.map = init_map(ctx.mode)
        $('#game').onclick = play
    }

    $('.mask button').onclick = () => {
        $('.mask').style.display = ''
    }
}

function init(mode) {
    render_checkerboard(mode)
    $('.reset-btn').click()
}

export { bind_event, init };